﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    internal class godown
    {
        model m;
        internal godown(string 下载地址, string 保存路径, string 文件名)
        {
            m = new model();
            m.状态 = 1;
            m.下载地址 = 下载地址;
            m.保存路径 = 保存路径;
            m.文件名 = 文件名;
            m.guid = Guid.NewGuid().ToString();
            //判断是否有此路径，没有的话创建
            tool.AddFill(保存路径);
        }
        private DateTime time = DateTime.Now;
        private WebClient webClient = new WebClient();

        /// <summary>
        /// 返回model
        /// </summary>
        /// <returns></returns>
        internal model star()
        {
            System.Net.ServicePointManager.DefaultConnectionLimit = 50;
            webClient.Proxy = null;
            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;//下载中
            webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;//下载完成

            time = DateTime.Now;
            webClient.DownloadFileAsync(new Uri(m.下载地址), m.保存路径 + m.文件名);
            m.wc = webClient;
            return m;
        }

        

        /// <summary>
        /// 下载中，进度回写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            //每秒读一次
            if ((DateTime.Now - time).Seconds < 1) { return; }
            time = DateTime.Now;
            long x = e.BytesReceived;

            m.状态 = 1;
            m.下载速度_Byte = (x - m.下载了多少Byte);
            m.下载了多少Byte = x;
            m.文件总大小Byte = e.TotalBytesToReceive;
            m.进度 = e.ProgressPercentage;

            //((WebClient)a).QueryString["seed"] = (e.BytesReceived - m.下载了多少Byte).ToString();
            //((WebClient)a).QueryString["已经下载"] = b.BytesReceived.ToString();

        }

        /// <summary>
        /// 下载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            //下载完成
            if (e.Error != null)
            {
                //出现错误
                m.状态 = 3;
                m.错误信息 = e.Error.Message;
            }
            else
            {
                m.状态 = 2;
                m.进度 = 100;
                m.下载速度_Byte = 0;
                m.下载了多少Byte = m.文件总大小Byte;
            }
            webClient.Dispose();
        }
    }
}
